#!/usr/bin/python
# 
# Copyright (C) 2009 Frank Ronny Larsen.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Subset of string.printable, removing \t\n etc.
printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ '

def hextext(text):
    hexbuf = u""
    index = 0
    lines = []
    while text:
        workline = text[0:16]
        hexes = u" ".join([u"%02x" % ord(ch) for ch in workline])
        if len(workline) < 16:
            hexes += ("%%%ds" % (48-(len(workline)*3))) % ""
        rawstr = [ch in printable and ch or "." for ch in workline]
        rawstr = "".join(rawstr)
        tmpstr = u"%08x  %s  %s" % (index, hexes, rawstr)
        lines.append(tmpstr)
        index += 16
        text = text[16:]
    ret = "\n".join(lines)
    print ret
    return ret

